package com.hisense.proxy.busitrans.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.hisense.proxy.busitrans.vo.HxFdcprBusitransApplyInvoiceBodyDetailVO;
import com.hisense.proxy.busitrans.vo.HxFdcprBusitransApplyInvoiceHeadVO;

import lombok.extern.slf4j.Slf4j;

public class MergeInvoiceDetailUtil {
	
    private static Logger log = LoggerFactory.getLogger(MergeInvoiceDetailUtil.class);

	protected static void mergeBodyDetail(HxFdcprBusitransApplyInvoiceHeadVO bodyData) {
		
		log.info("Requesting apply invoice body  : {}", JSON.toJSONString(bodyData));
		
		List<HxFdcprBusitransApplyInvoiceBodyDetailVO> result = new ArrayList<HxFdcprBusitransApplyInvoiceBodyDetailVO>();
		
		List<HxFdcprBusitransApplyInvoiceBodyDetailVO> details = bodyData.getDetails();
		Map<String, List<HxFdcprBusitransApplyInvoiceBodyDetailVO>> collect = details.stream().collect(Collectors.groupingBy(
				item -> item.getChargeNamePk()));
//		item -> item.getDetailType() + "_" + item.getChargeNamePk() + "_" + item.getHousePk()));

		
		Iterator<Entry<String, List<HxFdcprBusitransApplyInvoiceBodyDetailVO>>> iterator = collect.entrySet().iterator();
		while(iterator.hasNext()) {
			Entry<String, List<HxFdcprBusitransApplyInvoiceBodyDetailVO>> next = iterator.next();
			List<HxFdcprBusitransApplyInvoiceBodyDetailVO> value = next.getValue();
			if (value.size() == 0) {
				continue;
			}
			
			double amount = 0;
			for (HxFdcprBusitransApplyInvoiceBodyDetailVO item : value) {
				amount += item.getNallbrevmny();
			}
			
			HxFdcprBusitransApplyInvoiceBodyDetailVO seed = value.get(0);
			seed.setNallbrevmny(amount);
			result.add(seed);
		}
		
		bodyData.setDetails(result);
	}

}
